import { memo, useMemo } from "react";
import { DEFAULT_WIDTH, DEFAULT_HEIGHT } from "./constans";

const SelectLine = memo(({ active, rowWidth, colHeight, scrollX, scrollY }) => {
  const areaStyle = useMemo(() => {
    const { type, start, end } = active;
    if (!type) return {};
    if (type === "row") {
      let left = 0;
      let right = 0;
      for (let i = 0; i <= end; i++) {
        if (i === start) {
          left = right;
        }
        right += rowWidth[i] || DEFAULT_WIDTH;
      }
      return {
        left,
        right,
        top: 0,
        height: `calc(100% + ${scrollY + 200}px)`,
      };
    }
    if (type === "col") {
      let top = 0;
      let bottom = 0;
      for (let i = 0; i <= end; i++) {
        if (i === start) {
          top = bottom;
        }
        bottom += colHeight[i] || DEFAULT_HEIGHT;
      }
      return {
        left: 0,
        width: `calc(100% + ${scrollX + 300}px)`,
        top,
        bottom,
      };
    }
    if (type === "cell") {
      let left = 0;
      let right = 0;
      for (let i = 0; i <= end[0]; i++) {
        if (i === start[0]) {
          left = right;
        }
        right += rowWidth[i] || DEFAULT_WIDTH;
      }

      let top = 0;
      let bottom = 0;
      for (let i = 0; i <= end[1]; i++) {
        if (i === start[1]) {
          top = bottom;
        }
        bottom += colHeight[i] || DEFAULT_HEIGHT;
      }
      return {
        left,
        right,
        top,
        bottom,
      };
    }
  }, [active, rowWidth, colHeight, scrollX, scrollY]);

  return [
    <div
      className="select-line select-top"
      key="top"
      style={{
        top: `${areaStyle.top}px`,
        width: areaStyle.width || `${areaStyle.right - areaStyle.left}px`,
        left: `${areaStyle.left}px`,
      }}
    ></div>,
    <div
      className="select-line select-left"
      key="left"
      style={{
        top: `${areaStyle.top}px`,
        left: `${areaStyle.left}px`,
        height: areaStyle.height || `${areaStyle.bottom - areaStyle.top}px`,
      }}
    ></div>,
    <div
      className="select-line select-right"
      key="right"
      style={{
        top: `${areaStyle.top}px`,
        left: areaStyle.width ? "" : `${areaStyle.right - 2}px`,
        height: areaStyle.height || `${areaStyle.bottom - areaStyle.top}px`,
      }}
    ></div>,
    <div
      className="select-line select-bottom"
      key="bottom"
      style={{
        top: areaStyle.height ? "" : `${areaStyle.bottom - 2}px`,
        left: `${areaStyle.left}px`,
        width: areaStyle.width || `${areaStyle.right - areaStyle.left}px`,
      }}
    ></div>,
  ];
});

export default SelectLine;
